package com.hr.dao.impl;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.hr.dao.AdminDao;
import com.hr.pojo.Admin;
import com.hr.utils.C3P0Utils;
public class AdminDaoImpl implements AdminDao {
	private QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
	@Override
	public Admin findUserByUsernameAndPassword(String username, String password) {
		String sql ="select * from hr_admin where username= ?";
		Object[] params = new Object[]{username};
		Admin user = null;
		try {
			user = queryRunner.query(sql, new BeanHandler(Admin.class),params);
		} catch (SQLException e) {
			return (null);
			
		}
		return user;	
	}

	@Override
	public void saveUser(Admin user) {
		/**
		 * 日期格式化
		 */
		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		user.setCreatetime(Timestamp.valueOf(simpleDate.format(user.getCreatetime())));
		String sql ="insert into hr_admin(username,password,sex,birthday,createtime,content,ifadmin) values(?,?,?,?,?,?,?)";
		Object[] params = new Object[]{user.getUsername(),user.getPassword(),user.getSex(),user.getBirthday(),user.getCreatetime(),user.getContent(),user.getIfadmin()};
		try {
			queryRunner.update(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	@Override
	public List findAllUsers() {
		String sql ="select * from hr_admin";
		List<Admin> list = null;
		try {
			 list = queryRunner.query(sql, new BeanListHandler<Admin>(Admin.class) );
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	@Override
	public Admin findUserById(String id) {
		String sql ="select * from hr_admin where id = ?";
		Admin user = null;
		try {
			user = queryRunner.query(sql,new BeanHandler<>(Admin.class),id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return user;
	}
	@Override
	public void updateUser(Admin user) {
		if(user.getPassword()!=null) {
			String sql ="update hr_admin set username=?,password=?,sex=?,birthday=?,content=? where id=? ";		
			Object[] params={user.getUsername(),user.getPassword(),user.getSex(),user.getBirthday(),user.getContent(),user.getId()};
			try {
				queryRunner.update(sql, params);
			} catch (SQLException e) {
				e.printStackTrace();
			}	
		}else {
			String sql= "update hr_admin set username=?,sex=?,birthday=?,content=? where id=? ";
			Object[] params={user.getUsername(),user.getSex(),user.getBirthday(),user.getContent(),user.getId()};
			try {
				queryRunner.update(sql, params);
			} catch (SQLException e) {
				e.printStackTrace();
			}	
		}

	}
	
	@Override
	public void delete(String id) {
		String sql ="delete from hr_admin where id =? ";
		try {
			queryRunner.update(sql, id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
